package com.cchc.k8s.apis;

import com.alibaba.fastjson.JSONObject;
import com.cchc.k8s.config.K8sException;
import com.cchc.k8s.kernel.ServiceBuilder;
import com.cchc.k8s.request.CreateServiceRequest;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Service;
import io.kubernetes.client.openapi.models.V1ServiceList;
import io.kubernetes.client.openapi.models.V1Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * file：ServiceApi.java
 * description: Service操作api
 * date: 2021-09-17 16:19
 * author: wenrui
 * version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/svc")
public class ServiceApi {

    @Autowired
    ApiClient apiClient;
    @Autowired
    ServiceBuilder serviceBuilder;

    /**
     * 创建Service
     *
     * @param nsName  命名空间名称
     * @param request 请求信息
     * @return Service信息
     */
    @PostMapping("/create/{nsName}")
    public V1Service createService(@PathVariable String nsName, @RequestBody CreateServiceRequest request) {
        log.info("创建命名空间：{}的Service，请求参数为：{}", nsName, JSONObject.toJSONString(request));
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        V1Service v1Service;
        try {
            V1Service service = serviceBuilder.build(request);
            v1Service = coreV1Api.createNamespacedService(nsName, service, "true", null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            log.error("创建命名空间：{}的Service失败，原因：{}", nsName, e.getResponseBody());
            throw new K8sException("S" + e.getCode(), (String) JSONObject.parseObject(e.getResponseBody()).get("message"));
        }

        log.info("创建命名空间：{}的Service成功，返回信息为：{}", nsName, v1Service.toString());
        return v1Service;
    }

    /**
     * 删除Service
     *
     * @param nsName      命名空间名称
     * @param serviceName Service名称
     * @return V1Status
     */
    @DeleteMapping("/delete/{nsName}/{serviceName}")
    public V1Status deleteService(@PathVariable String nsName, @PathVariable String serviceName) {
        log.info("删除命名空间：{}下的Service：{}", nsName, serviceName);
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        V1Status v1Status;
        try {
            v1Status = coreV1Api.deleteNamespacedService(serviceName + "-svc", nsName, "true", null, null, null, null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            log.info("删除命名空间：{}下的Service：{}失败，信息：{}", nsName, serviceName, e.getResponseBody());
            throw new K8sException("S" + e.getCode(), (String) JSONObject.parseObject(e.getResponseBody()).get("message"));
        }
        if (v1Status != null && Objects.equals(v1Status.getStatus(), "Success")) {
            log.info("删除命名空间：{}下的Service：{}成功，信息：{}", nsName, serviceName, JSONObject.toJSONString(v1Status));
        }
        return v1Status;
    }

    /**
     * 查询Service列表
     *
     * @param nsName 命名空间名称
     * @return Service列表
     */
    @GetMapping("/list/{nsName}")
    public V1ServiceList listService(@PathVariable String nsName) {
        log.info("获取命名空间：{}下的Service列表", nsName);
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        V1ServiceList v1ServiceList;
        try {
            v1ServiceList = coreV1Api.listNamespacedService(nsName, "true", null, null, null, null, null, null, null, null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            log.info("获取命名空间：{}下的Service列表失败，信息：{}", nsName, e.getResponseBody());
            throw new K8sException("S" + e.getCode(), (String) JSONObject.parseObject(e.getResponseBody()).get("message"));
        }
        log.info("获取命名空间：{}下的Service列表,响应信息为：{}", nsName, v1ServiceList.toString());
        return v1ServiceList;
    }

    /**
     * 查询Service详情
     *
     * @param nsName      命名空间名称
     * @param serviceName Service名称
     * @return Service详情
     */
    @GetMapping("/detail/{nsName}/{serviceName}")
    public V1Service detailService(@PathVariable String nsName, @PathVariable String serviceName) {
        log.info("获取命名空间：{}下的Service:{}详情", nsName, serviceName);
        CoreV1Api coreV1Api = new CoreV1Api(apiClient);
        V1Service v1Service;
        try {
            v1Service = coreV1Api.readNamespacedService(serviceName + "-svc", nsName, "true", null, null);
        } catch (ApiException e) {
            e.printStackTrace();
            log.info("获取命名空间：{}下的Service{}详情失败，信息：{}", nsName, serviceName, e.getResponseBody());
            throw new K8sException("S" + e.getCode(),(String) JSONObject.parseObject(e.getResponseBody()).get("message"));
        }
        log.info("获取命名空间：{}下的Service:{}详情, 响应信息为：{}", nsName, serviceName, v1Service.toString());
        return v1Service;
    }
}
